//
//  UserOrderDetailsVC.m
//  WoWeiRenRenOC
//
//  Created by 姜孟东 on 2020/6/13.
//  Copyright © 2020 姜孟东. All rights reserved.
//

#import "UserOrderDetailsVC.h"
#import "MailConfirmOrderVC.h"
#import "MailConfirmOrderHeadView.h"
#import "MailConfirmOrderGoodsCell.h"
#import "MailConfirmOrderFooterView.h"
#import "MailConfirmOrderBottomView.h"
#import "UserOrderDetailsHeadView.h"
#import "UserOrderChildCell.h"
#import "UserOrderDetailsShowCell.h"
#import "UserOrderDetailsBottomView.h"
#import "UserShoppingOrderDetailsModel.h"
#import "UserShoppingOrderDetailsLogisticsView.h"
#import "OrderPayVC.h"
#import "PagingViewController.h"
#import "UserOrderChildGroupView.h"
#import "UserOrderDetailsQRCodeCell.h"
#import "MailDetailsVC.h"
#import "ReFundOrderSelectorVC.h"
#import "QueryGoodsLogisticsVC.h"

@interface UserOrderDetailsVC ()

@property (nonatomic,strong) UserOrderDetailsHeadView *headView;

@property (strong, nonatomic)UserOrderDetailsBottomView *bottomView;

@property (strong, nonatomic)NSMutableArray *cellContentArray;

@property (strong, nonatomic)UserShoppingOrderDetailsModel *model;
@end

@implementation UserOrderDetailsVC

- (void)viewDidLoad {
    [super viewDidLoad];
        
    
    self.defaultStartPage = 1;
    self.title = @"订单详情";
    
    
//    [self creatTableViewWithCellIdentity:@"UserOrderChildCell"];
    [self creatTableViewStyle:UITableViewStyleGrouped cellIdentity:@"UserOrderChildCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"UserOrderDetailsShowCell" bundle:nil] forCellReuseIdentifier:@"UserOrderDetailsShowCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"UserOrderDetailsQRCodeCell" bundle:nil] forCellReuseIdentifier:@"UserOrderDetailsQRCodeCell"];
    
    self.view.backgroundColor = WhiteColor;
    self.tableView.backgroundColor = WhiteColor;
    self.tableView.rowHeight = 110;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.frame = CGRectMake(0, NavBarHeight, kScreenW, kScreenH-NavBarHeight -NeedStatusViewHeight);
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 50, 0);
    self.tableView.tableHeaderView = self.headView;
    
    
    [self.view addSubview:self.bottomView];
    [self requestData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestData) name:kUserOrderDetilsUpDate object:nil];
    
}



- (void)requestData
{
    SVPShowInternetWaiting
   // 请求列表
    [NetRequestTool postUrl:@"skuOrder/querySkuOrderInfo" parameters:@{@"order_code":self.order_code} success:^(id responseObject) {
        
        self.model = [UserShoppingOrderDetailsModel mj_objectWithKeyValues:responseObject[@"object"]];
        self.cellContentArray = [NSMutableArray array];
        if (self.model.order_type == 99) {
            [self setSkuLBInfo];
        }else {
            [self setSkuInfo];
        }
        
 
        self.headView.model = self.model;
        if ([CommonTTool isStrNull:self.model.address_id]) {
            self.headView.frame = CGRectMake(0, 0, KSCREEN_WIDTH, 85);
        }
        
        
        self.bottomView.model = self.model;
        
        [self.tableView reloadData];
        
        
    } failure:^(NSInteger statusCode) {
        
    } finish:^{
        
    }];
    
}


- (void)setSkuInfo {
    
    [self.cellContentArray addObject:@{@"title":@"商品金额",@"content":[NSString stringWithFormat:@"￥%@",[CommonTTool  getPrice:self.model.sku_price]]}];
     NSString *freight = @"";
     if (self.model.order_type != 3 && self.model.order_type != 9) {
         if (self.model.freight_price == 0) {
             freight = @"包邮";
         }else {
             freight = [NSString stringWithFormat:@"￥%@",[CommonTTool  getPrice:self.model.freight_price]];
         }
         [self.cellContentArray addObject:@{@"title":@"运费金额",@"content":freight}];

     }
     
     [self.cellContentArray addObject:@{@"title":@"付款金额",@"content":[NSString stringWithFormat:@"￥%@",[CommonTTool  getPrice:self.model.pay_price]]}];
     if (self.model.order_state == 3 || self.model.order_state == 4 || self.model.order_state == 5) {
         NSString *pay_type = self.model.pay_type == 1 ? @"支付宝支付":@"微信支付";
         [self.cellContentArray addObject:@{@"title":@"支付方式",@"content":pay_type}];
         [self.cellContentArray addObject:@{@"title":@"支付时间",@"content":self.model.pay_time}];
     }
     [self.cellContentArray addObject:@{@"title":@"创建时间",@"content":self.model.create_time}];
     [self.cellContentArray addObject:@{@"title":@"订单编号",@"content":self.model.order_code}];
     if (![CommonTTool isStrNull:self.model.remark]) {
         [self.cellContentArray addObject:@{@"title":@"订单备注",@"content":self.model.remark}];
     }
    
}

- (void)setSkuLBInfo {
    
    [self.cellContentArray addObject:@{@"title":@"商品金额",@"content":@"免费"}];
    [self.cellContentArray addObject:@{@"title":@"订单类型",@"content":@"新注册会员礼包"}];
     
     [self.cellContentArray addObject:@{@"title":@"创建时间",@"content":self.model.create_time}];
     [self.cellContentArray addObject:@{@"title":@"订单编号",@"content":self.model.order_code}];
     if (![CommonTTool isStrNull:self.model.remark]) {
         [self.cellContentArray addObject:@{@"title":@"订单备注",@"content":self.model.remark}];
     }
    
}





- (UserOrderDetailsHeadView *)headView {
 
    if (!_headView) {
       
        _headView = [[NSBundle mainBundle] loadNibNamed:@"UserOrderDetailsHeadView" owner:self options:nil].lastObject;
        _headView.frame = CGRectMake(0, 0, kScreenW, 160);
        
    }
    
    return _headView;
}



- (UserOrderDetailsBottomView *)bottomView {
    
    if (!_bottomView) {
        
        _bottomView = [[NSBundle mainBundle] loadNibNamed:@"UserOrderDetailsBottomView" owner:self options:nil].lastObject;
        _bottomView.frame = CGRectMake(0, KSCREEN_HEIGHT -110 -NeedStatusViewHeight, kScreenW, 90);
        [_bottomView.paymentBtn addTarget:self action:@selector(paymentBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView.LogisticsBtn addTarget:self action:@selector(showLogisticsView) forControlEvents:UIControlEventTouchUpInside];
        
        [_bottomView.goodsBtn addTarget:self action:@selector(goodsBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView.reFundBtn addTarget:self action:@selector(reFundBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _bottomView;
}
#pragma mark - 申请退款
- (void)reFundBtnClick {
    
    if (self.model.order_state == 4) {
        ReFundOrderSelectorVC *vc = [[ReFundOrderSelectorVC alloc]init];
        vc.model = self.model;
        vc.order_code = self.order_code;
        [self.navigationController pushViewController:vc animated:YES];
        
        return;
    }
    
    UIAlertController *alterController = [UIAlertController alertControllerWithTitle:nil message:@"是否确认申请退款？" preferredStyle:UIAlertControllerStyleAlert];
    [alterController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }]];
    
    [alterController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSMutableArray *goods_order_detail_list = [NSMutableArray array];

        for (MailGoodsDetailsModel *superModel in self.model.sku_order_detail_list) {
   
            NSDictionary *dict = @{@"sku_id":superModel.sku_id,
                                   @"t_num":@(superModel.num)
                           };
            [goods_order_detail_list addObject:dict];
           
        }
        NSData *dataFriends = [NSJSONSerialization dataWithJSONObject:goods_order_detail_list options:NSJSONWritingPrettyPrinted error:nil];

        NSString *jsonString = [[NSString alloc] initWithData:dataFriends encoding:NSUTF8StringEncoding];
        SVPShowInternetWaiting;
        [NetRequestTool postUrl:@"skuOrder/refundOrder" parameters:@{@"order_code":self.order_code,@"order_detail_list":jsonString} success:^(id responseObject) {
            [self requestData];
            [[NSNotificationCenter defaultCenter] postNotificationName:kUserOrderTableUpDate object:nil];

        } failure:^(NSInteger statusCode) {
           
        } finish:^{
           
        }];
        
    }]];
    
    [[CommonTTool getCurrentVC] presentViewController:alterController animated:YES completion:nil];
    
}

#pragma mark - 确认收货
- (void)goodsBtnClick {
    
    // 系统提示框
    UIAlertController *alterController = [UIAlertController alertControllerWithTitle:nil message:@"是否确认收货？" preferredStyle:UIAlertControllerStyleAlert];
    [alterController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        
    }]];
    
    [alterController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        SVPShowInternetWaiting;
        [NetRequestTool postUrl:@"skuOrder/confirmShOrder" parameters:@{@"order_code":self.order_code} success:^(id responseObject) {
            [self requestData];
            [[NSNotificationCenter defaultCenter] postNotificationName:kUserOrderTableUpDate object:nil];

        } failure:^(NSInteger statusCode) {
           
        } finish:^{
           
        }];
        
    }]];
    
    [[CommonTTool getCurrentVC] presentViewController:alterController animated:YES completion:nil];
    
}

#pragma mark - 支付
- (void)paymentBtnClick {
    
    
    MailGoodsDetailsModel *model = self.model.sku_order_detail_list[0];
    
    SVPShowInternetWaiting;
    [NetRequestTool postUrl:@"skuOrder/getPayOrderCode" parameters:@{@"order_code":self.order_code} success:^(id responseObject) {
        NSString *order = responseObject[@"object"];
        OrderPayVC *vc = [[OrderPayVC alloc]init];
        vc.type = self.model.order_type;
        vc.parent_order_code = order;
        vc.is_ht = model.is_ht;
        [self.navigationController pushViewController:vc animated:YES];
        
    } failure:^(NSInteger statusCode) {
        
    } finish:^{
        
    }];
    
   
    
}


#pragma mark - 显示物流编号
- (void)showLogisticsView {
    
//    UserShoppingOrderDetailsLogisticsView*view = [UserShoppingOrderDetailsLogisticsView showView];
//    view.nameLabel.text = self.model.express_org;
//    view.codeLabel.text = self.model.express_no;
    
    QueryGoodsLogisticsVC *vc = [[QueryGoodsLogisticsVC alloc]init];
    vc.order_code = self.model.order_code;
    [[CommonTTool getCurrentVC].navigationController pushViewController:vc animated:YES];
    
}

    
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2) {
        
        
        UserOrderDetailsQRCodeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserOrderDetailsQRCodeCell"];
        cell.model = self.model;
        tableView.rowHeight = 300;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
        
    }else if (indexPath.section == 0) {
        
        UserOrderChildCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserOrderChildCell"];
        cell.model = self.model.sku_order_detail_list[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (cell.model.is_td == 5 || cell.model.is_td == 2 || cell.model.is_td == 6) {

            
            cell.reFundLabel.hidden = NO;
            cell.reFundCoutnLabel.hidden = NO;
            tableView.rowHeight = 150;
        }else {
            
            cell.reFundLabel.hidden = YES;
            cell.reFundCoutnLabel.hidden = YES;
            tableView.rowHeight = 110;
        }
        return cell;
        
    }else {
        
        UserOrderDetailsShowCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserOrderDetailsShowCell"];
               //cell.model = self.dataArray[indexPath.row];
        NSDictionary *model = self.cellContentArray[indexPath.row];
        cell.nameLabel.text = model[@"title"];
        cell.contentLabel.text = model[@"content"];
        if ([cell.nameLabel.text isEqualToString:@"商品金额"] || [cell.nameLabel.text isEqualToString:@"运费金额"] || [cell.nameLabel.text isEqualToString:@"付款金额"]) {
            cell.contentLabel.textColor = kRGBAColor(198, 1, 34, 1);
        }else {
            cell.contentLabel.textColor = BlackColor;
        }
        if ([cell.nameLabel.text isEqualToString:@"订单编号"]) {
            cell.contentLabel.text = [NSString stringWithFormat:@"%@[复制]",cell.contentLabel.text];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(copyOrderCode)];
            cell.contentLabel.userInteractionEnabled = YES;
            [cell.contentLabel addGestureRecognizer:tap];
        }
        tableView.rowHeight = UITableViewAutomaticDimension;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        MailGoodsDetailsModel *model = self.model.sku_order_detail_list[indexPath.row];
        MailDetailsVC *vc = [[MailDetailsVC alloc] init];
        vc.goodsModel = model;
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
           
    }
    
    
}

- (void)copyOrderCode {
    
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];

    pasteboard.string = self.cellContentArray[self.cellContentArray.count - 1][@"content"];;

    SVP(@"订单编号已复制");
    
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 1) {
        
        return self.cellContentArray.count;
    }
    
    if (section == 2) {
        
        if (self.model.order_type == 3 || self.model.order_type == 9) {
            if (self.model.order_state >= 3) {
                return 1;
            }
            
            return 0;
        }
        
        return 0;
    }
    
    return self.model.sku_order_detail_list.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    
    return 3;
    
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        
         UserOrderChildGroupView *view = [[NSBundle mainBundle] loadNibNamed:@"UserOrderChildGroupView" owner:self options:nil].lastObject;
         view.nameLabel.text = self.model.business_name;

         view.jumpBtn.tag = section;
         [view.jumpBtn addTarget:self action:@selector(headVieTapClick:) forControlEvents:UIControlEventTouchUpInside];
         view.tag = section;
         
         return view;
        
    }else {
        
        UIView *view = [[UIView alloc]init];
        view.backgroundColor = kRGBColor(246, 246, 246);
        view.clipsToBounds = YES;
        
        return view;
        
    }
 
}

- (void)headVieTapClick:(UIButton *)view {
    
    PagingViewController *vc= [[PagingViewController alloc]init];
    vc.business_id = self.model.business_id;
    [self.navigationController pushViewController:vc animated:YES];
}




- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
         return 50;
    }else {
        return 0.0001f;
    }
   
}

@end
